<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建宣讲课程' : "编辑宣讲课程" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>

        <el-form-item label="课程类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择课程类型">
            <el-option v-for="(sItem, sIndex) in courseTypeList" :key="sIndex" :label="sItem.courseTypeName" :value="sItem.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程时长/分钟" prop="minute">
          <el-input-number
            v-model="ruleForm.minute"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入课程时长/分钟"
            :min="10"
          />
        </el-form-item>

        <el-form-item label="专家" prop="expertId">
          <el-select v-model="ruleForm.expertId" placeholder="请选择专家" filterable>
            <el-option v-for="(sItem, sIndex) in expertList" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="参与人次" prop="joinPeopleCount">
          <el-input-number
            v-model="ruleForm.joinPeopleCount"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入参与人次"
            :min="1"
          />
        </el-form-item> -->

        <!-- <el-form-item label="发布单位" prop="pubUnit">
          <el-input v-model="ruleForm.pubUnit" placeholder="请输入发布单位"></el-input>
        </el-form-item> -->

        <el-form-item label="是否推荐" prop="isRecommend">
          <el-select v-model="ruleForm.isRecommend" placeholder="请选择课程类型">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程简介" prop="description">
          <el-input v-model="ruleForm.description" autosize type="textarea" placeholder="请输入课程简介"></el-input>
        </el-form-item>

        <!-- <el-form-item label="评分" prop="mark">
          <el-input-number
            v-model="ruleForm.mark"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入评分"
            :min="0"
          />
        </el-form-item> -->

        <el-form-item label="封面图片" prop="coverUrl">
          <el-image style="width: 313px;"
            :src="imageUrl ? imageUrl : ''" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-image style="width: 313px;" src="/images/course_default.png" fit="cover" />
              </div>
            </template>
          </el-image>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传封面图片
          </el-button>
          <span style="margin-left: 10px;">请上传不超过10M的图片，格式：jpg/png/jpeg</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCourseAdd" }
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getCourseDetail()
  }

  getExpertList()
  /* 如果是从专家列表跳转过来，默认选中此专家 */
  if(route.currentRoute.value.query.expertId){
    ruleForm.value.expertId = route.currentRoute.value.query.expertId
  }
  
  getCourseTypeList()
  
  /* 课程分类跳转过来，默认选中此分类 */
  if(route.currentRoute.value.query.courseTypeId){
    ruleForm.value.type = route.currentRoute.value.query.courseTypeId
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getCourseDetail = () => {
  loading.value = true
  http.$GET("/PreachM/GetPreachCourseDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理数值 */
    ruleForm.value.minute = Number(res.result.minute)
    ruleForm.value.joinPeopleCount = Number(res.result.joinPeopleCount)

    /* 课程封面图片路径 */
    if(!isJsonString(res.result.coverUrl)){
      imageUrl.value = ""
      ruleForm.value.coverUrl = ""
      return
    }
    if(res.result.coverUrl != ''){
      let picture = JSON.parse(res.result.coverUrl)

      if(picture.filePathArray){
        imageUrl.value = import.meta.env.VITE_APP_STATIC_URL + picture.filePathArray[0].CompleteFilePath
      }else{
        imageUrl.value = ""
        ruleForm.value.coverUrl = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 专家下拉列表请求 */
const expertList = ref([])
const expertPageIndex = ref(1)
const expertPageSize = ref(1000)

const getExpertList = () => {
  let params = {
    pageIndex: expertPageIndex.value,
    pageSize: expertPageSize.value,
    dfi: {
      Logic: 0,
      Filters: [{
        Field: "expertType",
        Operator: 0,
        Value: "宣讲专家"
      }]
    },
  }
  http.$POST(`/TheoryStudyM/GetExpertInfoList`, params).then(res => {
    expertList.value = expertList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      expertPageIndex.value = expertPageIndex.value + 1
      getExpertList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 课程类型下拉列表请求 */
const courseTypeList = ref([])
const coursePageIndex = ref(1)
const coursePageType = ref(200)

const getCourseTypeList = () => {
  let params = {
    pageIndex: coursePageIndex.value,
    pageSize: coursePageType.value
  }
  http.$POST(`/PreachM/GetPreachCourseTypeInfoList`, params).then(res => {
    courseTypeList.value = courseTypeList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      coursePageIndex.value = coursePageIndex.value + 1
      getCourseTypeList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}
/* 表单 */
const ruleFormRef = ref(null)

/* 表单数据 */
const ruleForm = ref({
  id: "",
  title: "",
  type: "",
  minute: null,
  /* joinPeopleCount: null, */
  /* pubUnit: "", */
  isRecommend: "",
  description: "",
  /* mark: null, */
  coverUrl: "",
  expertId: "",
})

/* 封面图片路径 */
const imageUrl = ref(null)
/* 是否有上传图片 */
const isUploadImage = ref(false)

/* 封面图片校验规则 */
const checkFile = (rule, value, callback) => {
  if (!ruleForm.value.coverUrl) {
    callback(new Error('请上传封面图片'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  type: [
    { required: true, message: '请选择课程类型', trigger: 'change' }
  ],
  minute: [
    { required: true, message: '请输入课程时长', trigger: 'blur' },
  ],
  /* joinPeopleCount: [
    { required: true, message: '请填写参与人次', trigger: 'blur' }
  ], */
  /* pubUnit: [
    { required: true, message: '请填写发布单位', trigger: 'blur' }
  ], */
  isRecommend: [
    { required: true, message: '请选择是否推荐', trigger: 'change' }
  ],
  expertId: [
    { required: true, message: '请输入专家', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请填写课程简介', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  /* mark: [
    { required: true, message: '请填写评分', trigger: 'blur' }
  ], */
  /* coverUrl: [
    { required: true, validator: checkFile, message: '请上传封面图片', trigger: 'change' }
  ], */
})

/* 点击上传文件 */
const uploadEvent = () => {

  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG)$/)){
      ruleForm.value.coverUrl = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }
    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.coverUrl = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadImage.value = true
      ruleForm.value.coverUrl = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('coverUrl')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if(!isUploadImage.value) {
        delete ruleForm.value.coverUrl
      }

      http.$POST("/PreachM/AddOrUpdatePreachCourseInfo", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');
          route.push({
            path: "/backend/publicize-course"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ""
  isUploadImage.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/publicize-course",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>